package com.slkj.util;

import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import java.io.UnsupportedEncodingException;

@Component
public class CookieTools {

    public void save(String name, String value, int maxAge) throws UnsupportedEncodingException {
        value = java.net.URLEncoder.encode(value, "utf-8");
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(maxAge);
        RequestResponseBox.getResponse().addCookie(cookie);

    }

    public void delete(String name) {
        Cookie cookie = new Cookie(name, "");
        cookie.setMaxAge(0);
        RequestResponseBox.getResponse().addCookie(cookie);
    }

    public String get(String name) throws UnsupportedEncodingException {
        String value = null;
        Cookie[] cookies = RequestResponseBox.getRequest().getCookies();
        if (cookies != null && cookies.length != 0) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if (cookie.getName().equals(name)) {
                    value = cookie.getValue();
                    value = java.net.URLDecoder.decode(value, "utf-8");

                }
            }
        }
        return value;
    }


}
